package com.gy.mbaselibrary.download;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;

import java.util.HashMap;
import java.util.Map;

/**
 * 创建者：高业
 * 邮箱：15234150168@163.com
 * 时间：2018/2/6
 * 描述：
 * 修改人：
 * 修改时间：2018/2/6
 * 修改备注：
 */
public class DownloadManager {
    private static int size = 5;


    public static class Builder{
        private String title;
        private String mes;
        private boolean isNotify;
        private Context context;
        private String url;

        public Builder(Context context){
            this.context = context;
        }

        private Builder(){

        }

        public Builder setUrl(String url) {
            this.url = url;
            return this;
        }

        public boolean isNotify() {
            return isNotify;
        }

        public Builder setNotify(boolean notify) {
            isNotify = notify;
            return this;
        }



        public String getTitle() {
            return title;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public String getMes() {
            return mes;
        }

        public Builder setMes(String mes) {
            this.mes = mes;
            return this;
        }

        public DownloadManager starTask(){
            DownloadManager manager = getManager(context);
            manager.startDownlaod(url,isNotify,title,mes);
            return manager;
        }
    }
    private AddFailListener addFailListener;
    private UpdateListener updateListener;
    private FinishListener finishListener;
    private static DownloadManager manager;
    private Context context;
    private DownLoadBroadcast downLoadBroadcast;
    private Map<String,DownloadManagerUtil> downMap = new HashMap<>();

    public static void init(int setSize){
        size = setSize;
    }

    public static synchronized DownloadManager getManager(Context context){
        if (manager == null){
            manager = new DownloadManager();
            manager.context = context;
            manager.registerBroadcast();
        }
        return manager;
    }

    public void onDestory(){
        unregisterBroadcast();
        for (Map.Entry<String, DownloadManagerUtil> entry : downMap.entrySet()) {
            entry.getValue().clearCurrentTask();
        }
        downMap.clear();
    }



    public DownloadManager setAddFailListener(AddFailListener addFailListener) {
        this.addFailListener = addFailListener;
        return this;
    }

    public DownloadManager setUpdateListener(UpdateListener updateListener) {
        this.updateListener = updateListener;
        return this;
    }

    public DownloadManager setFinishListener(FinishListener finishListener) {
        this.finishListener = finishListener;
        return this;
    }


    public void startDownlaod(final String url,boolean isNotify,String title,String mes){
        if (downMap.containsKey(url)){
            if (addFailListener != null)
                addFailListener.addFail(url,"此任务正在进行中");
            return;
        }

        if (downMap.size() >= size){
            if (addFailListener != null)
                addFailListener.addFail(url,"下载任务最大为" + size + "个");
            return;
        }

        if (downMap.size() < size && !downMap.containsKey(url)){
            DownloadManagerUtil downloadManagerUtil = new DownloadManagerUtil(context,url);

            downloadManagerUtil.setUpdateListener(new DownloadManagerUtil.UpdateListener() {
                @Override
                public void update(long downloadId, float percent) {
                    if (updateListener != null)
                        updateListener.update(url,(int)percent);
                }
            });
            downMap.put(url,downloadManagerUtil);
            if (isNotify){
                downloadManagerUtil.download(title,mes);
            }else {
                downloadManagerUtil.download();
            }

        }
    }


    public interface AddFailListener{
        public void addFail(String url, String message);
    }

    public interface UpdateListener{
        public void update(String url, float percent);
    }

    public interface FinishListener{
        public void finish(String url,String path);
    }

    public void stopDownload(String url){
        if (downMap.containsKey(url)){
            downMap.get(url).clearCurrentTask();
            downMap.remove(url);
        }
    }

    /**
     * 接受下载完成广播
     */
    private class DownLoadBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            long downId = intent.getLongExtra(android.app.DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            switch (intent.getAction()) {
                case android.app.DownloadManager.ACTION_DOWNLOAD_COMPLETE:
                    DownloadManagerUtil downloadManagerUtil = findById(downId);
                    downMap.remove(downloadManagerUtil.getUrl());
                    if (finishListener != null)
                        finishListener.finish(downloadManagerUtil.getUrl(),downloadManagerUtil.getPath());
                    break;
                case android.app.DownloadManager.ACTION_NOTIFICATION_CLICKED:
                    //ToastUitl.showToast("我被点击啦！");
                    break;
            }
        }
    }

    private DownloadManagerUtil findById(long downId) {
        for (Map.Entry<String, DownloadManagerUtil> entry : downMap.entrySet()) {
            if (entry.getValue().getDownloadId() == downId){
                return entry.getValue();
            }
        }
        return null;
    }

    /**
     * 注册广播
     */
    private void registerBroadcast() {
        /**注册service 广播 1.任务完成时 2.进行中的任务被点击*/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(android.app.DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        intentFilter.addAction(android.app.DownloadManager.ACTION_NOTIFICATION_CLICKED);
        context.registerReceiver(downLoadBroadcast = new DownLoadBroadcast(), intentFilter);
    }

    /**
     * 注销广播
     */
    private void unregisterBroadcast() {
        if (downLoadBroadcast != null) {
            context.unregisterReceiver(downLoadBroadcast);
            downLoadBroadcast = null;
        }
    }
}
